package com.luke.star.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;
public abstract class HTTPUtils {
	
	private static final RequestConfig config = RequestConfig.custom()
			.setConnectTimeout(30000).setSocketTimeout(30000).build();
	
	public static String doPostJsonutf8(String url,String reqStr) throws IOException {

		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		// 创建Http Post请求
		HttpPost httpPost = new HttpPost(url);
		// 创建参数列表
		if(!StringUtils.isEmpty(reqStr)) {
			StringEntity strEnt = new StringEntity(reqStr.toString(),"utf-8");
			strEnt.setContentEncoding("utf-8");
			strEnt.setContentType("application/json");
			httpPost.setEntity(strEnt);
		}
		//执行http请求
		CloseableHttpResponse response = httpClient.execute(httpPost);
		String resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		return resultString;
	}
	
	public static String doGetUtf8(String url) throws IOException {
		
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpget = new HttpGet(url);
		httpget.setConfig(config);
		//执行http请求
		CloseableHttpResponse response = httpClient.execute(httpget);
		String resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		return resultString;
	}
	
	
	
	public static String getCharset(String contentType){
		if(contentType == null || contentType.length() == 0){
			return "utf-8";
		}
		String []types = contentType.split(";");
		for(String type:types){
			String charset[] = type.split("=");
			if(charset.length == 2 && charset[0].contains("charset")){
				return charset[1].trim();
			}
		}
		return null;
	}
	
	
	public static String getJson(String url,String param) {
		CookieStore cookieStore = new BasicCookieStore();
//		BasicClientCookie cookie = new BasicClientCookie("sessionidadms","5fa42b44ec9355bec999a24c1f6b0bbb");
//		cookieStore.addCookie(cookie);
		
		CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore)
					.setDefaultRequestConfig(config).build();
//		CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore)
//				.setProxy(new HttpHost("127.0.0.1",8888)).setDefaultRequestConfig(config).build();
		
		HttpPost post = new HttpPost(url);
		String result = null;
		try {
			StringEntity s = new StringEntity(param);
			s.setContentEncoding("UTF-8");
			s.setContentType("text/html");//发送json数据需要设置contentType
			post.setEntity(s);
			post.setHeader("Cookie", "sessionidadms=a4c6823f7909196190d002bdf19167f3");
			HttpResponse res = httpclient.execute(post);
			HttpEntity entity = res.getEntity();
			result = EntityUtils.toString(entity,"utf-8");// 返回json格式：
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return result;
		
	}
	
	public static String getRawHtml(String url) {
		//获取响应文件，即html，采用get方法获取响应数据
		CookieStore cookieStore = new BasicCookieStore();
		CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(config).setDefaultCookieStore(cookieStore).build();
		HttpGet httpget = new HttpGet(url);
		CloseableHttpResponse response = null;
		String resultString = null;
		GZIPInputStream gzin = null;
		for(int i = 0; i < 2;i++){
			try{
				response = httpclient.execute(httpget);
				int state = response.getStatusLine().getStatusCode();
				if(state == HttpStatus.SC_OK){
					HttpEntity entity = response.getEntity();
					Header header = entity.getContentEncoding();
					Header h = entity.getContentType();
//    			 System.out.println("--h  charset:"+getCharset(h!=null?h.getValue():null));
					if(header != null && header.toString().contains("gzip")){
						System.out.println("  "+header.getName()+"   "+header.getValue());
						InputStream inputStream = entity.getContent();
						gzin = new GZIPInputStream(inputStream);  
						InputStreamReader isr = new InputStreamReader(gzin,"utf-8");   
						BufferedReader br = new BufferedReader(isr);  
						StringBuffer sb = new StringBuffer();  
						String tempbf;  
						while ((tempbf = br.readLine()) != null) {  
							sb.append(tempbf);  
							sb.append("\r\n");  
						}  
						isr.close();  
						gzin.close(); 
						resultString = sb.toString();
					}else{
						resultString = EntityUtils.toString(response.getEntity(),"utf-8");
					}
				}else{
					resultString = EntityUtils.toString(response.getEntity(),"utf-8");
				}
			}catch(Exception e){
//    		 e.printStackTrace(); //多线程会有很多readtime out
			}
		}
		return resultString;
	}

	
	public static String unicodetoString(String unicode){  
		if(unicode==null || "".equals(unicode)){
			return unicode;
		}
		StringBuilder sb = new StringBuilder();  
		int i = -1;  
		int pos = 0;  
		while((i=unicode.indexOf("\\u", pos)) != -1){  
			sb.append(unicode.substring(pos, i));  
			if(i+5 < unicode.length()){  
				pos = i+6;  
				sb.append((char)Integer.parseInt(unicode.substring(i+2, i+6), 16));  
			}  
		}  
		return sb.toString();  
	} 
	
	public static String getWeekday(String dateString){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String weekday = "";
		try {
			Date date = sdf.parse(dateString);
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
			switch(dayofweek){
			case 2:weekday = "周一";break;
			case 3:weekday = "周二";break;
			case 4:weekday = "周三";break;
			case 5:weekday = "周四";break;
			case 6:weekday = "周五";break;
			case 7:weekday = "周六";break;
			case 1:weekday = "周日";break;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return weekday;
	}
	
}